package com.ltmonitor.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ltmonitor.entity.Department;
import com.ltmonitor.vo.PaginateResult;
import com.ltmonitor.web.util.JsonMessage;
import com.ltmonitor.web.util.OnlineUser;

import net.sf.json.JSONObject;
import net.sf.json.util.JSONTokener;

/**
 * 基本控制器功能，提供查询等服务
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/basicSlctAction")
public class BasicSlctAction extends PaginateAction{
	
	//日志
	private Logger mylog = log.getLogger(this.getClass());
	
	
	/**
	 * 输出错误信息
	 * @param msg 错误信息
	 */
	private void outError(String msg , Exception e) {
		System.out.println(msg);
		if(e != null) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据错误信息，返回相应的返回值
	 * @param errMsg 错误信息
	 * @param succMsg 成功信息
	 * @return 
	 */
	public static JsonMessage getReturnResult(String errMsg,String succMsg,Object data) {
		
		JsonMessage result = null;
		if(errMsg.equals("")) {
			//错误信息为空
			result = new JsonMessage(true, data);
			result.setMessage(succMsg);
		}else {
			//有错误信息
			result = new JsonMessage(false, errMsg);
			if(data != null) {
				result.setData(data);
			}
		}
		
		return result;
	}
	
	
	/**
	 * 基础查询请求，查询数据
	 * @param jsonStr
	 * @return
	 */
	@RequestMapping("/basicSelectData.action")
	@ResponseBody
	public JsonMessage selectData(@RequestBody String jsonStr) {
		JsonMessage result = null;
		String msg = "";
//		log.error("测试输出错误信息！");
//		mylog.debug("测试调试信息");
//		mylog.error("测试错误信息！");
		try {
			Map map = JSONObject.fromObject(jsonStr);
			
			// 用于获取用户权限信息
			OnlineUser user = super.getOnlineUser();
			
			if(map.get("queryId") != null && user != null) {
				String queryId = map.get("queryId").toString();
				
				//获取查询部门编号
				getBasicQueryData(user, map);
				
				List list = queryService.query(queryId, map);
				result = new JsonMessage(true,list);
//				System.out.println(list.toString());
			}else {
				msg = "基础查询数据-->获取查询条件语句失败！无法查询！";
			}
			
			if(result == null) {
				result = getReturnResult(msg, "", null);
			}
		} catch (Exception e) {
			// TODO: handle exception
			msg = "基础查询数据失败：" + e.getMessage();
			mylog.error(msg);
			result =  getReturnResult(msg, "", null);
		}
		
		return result;
	}
	
	
	/**
	 * 根据权限，查询数据，分步查询，第一步，根据权限查询车辆id，第二步，根据车辆id，查询相应数据
	 * @param jsonStr
	 * @return
	 */
	@RequestMapping("/selectDataByAuth.action")
	@ResponseBody
	public JsonMessage selectDataByAuth(@RequestBody String jsonStr){
		JsonMessage result = null;
		String msg = "";
		try {
			Map map = JSONObject.fromObject(jsonStr);
			// 用于获取用户权限信息
			OnlineUser user = super.getOnlineUser();
			
			if(map.get("queryId") != null && user != null) {				
				//获取查询部门编号
				getBasicQueryData(user, map);
				
				String queryIdVeh = "alarmSlct.selectVehDatasByAuth";//根据权限，获取车辆id
				List list = new ArrayList<String> ();//车辆列表
				List vehList = queryService.query(queryIdVeh, map);
				if(vehList.size() > 0) {
//					System.out.println("车辆列表数：" + vehList.size());
					for(int i=0 ; i<vehList.size() ; i++) {
						Map temp = (Map) vehList.get(i);
						if(temp.containsKey("vehicleId")) {
							list.add(temp.get("vehicleId").toString());							
						}
					}
				}
				//整合map,去除已使用条件
				map.put("vehicleIdList", list);//车辆列表存入map
				map.remove("userId");
				map.remove("depId");
				map.remove("depIdList");
				
				//开始查询
				String queryId = map.get("queryId").toString();
				List resultList = queryService.query(queryId, map);
				result = new JsonMessage(true,resultList);			
				
			}else {
				msg += "根据权限查询分页数据失败：无法获取查询语句！";
			}
			
			
			//获取返回结果
			if(result == null) {
				result = getReturnResult(msg, "", null);
			}
		} catch (Exception e) {
			// TODO: handle exception
			msg += "根据权限查询分页数据失败，查询参数：" + jsonStr + " ， 失败原因：" + e.getMessage();
			mylog.error(msg);
			result = getReturnResult(msg,"",null);
		}
		

		return result;
	}
	
	
	/**
	 * 基础分页查询请求 
	 * @param jsonStr
	 * @return
	 */
	@RequestMapping("/basicSelectPaginationData.action")
	@ResponseBody
	public JsonMessage selectPaginationData(@RequestBody String jsonStr) {
		JsonMessage result = null;
		String msg = "";
//		log.error("测试输出错误信息！");
//		mylog.debug("测试调试信息");
//		mylog.error("测试错误信息！");
		try {
			Map map = JSONObject.fromObject(jsonStr);
			// 用于获取用户权限信息
			OnlineUser user = super.getOnlineUser();
			
			if(map.get("queryId") != null && user != null) {
				String queryId = map.get("queryId").toString();
				
				//获取查询部门编号
				getBasicQueryData(user, map);
				
				
				int pageNum = 1;//默认分页设置
				int pageSize = 0;
				if(map.get("pageNumber") != null) {
					pageNum = Integer.valueOf(map.get("pageNumber").toString());
				}
				if(map.get("pageSize") != null) {
					pageSize = Integer.valueOf(map.get("pageSize").toString());
				}
				if(pageSize > 0) {
					PaginateResult list = queryService.queryByPagination(queryId, map, pageNum, pageSize);					
					result = new JsonMessage(true,list);
				}else {
					msg += "分页数量参数获取失败！";
				}
//				System.out.println(list.toString());
			}else {
				msg = "基础分页查询数据-->获取查询条件语句失败！无法查询！";
			}
			
			if(result == null) {
				result = getReturnResult(msg, "", null);
			}
		} catch (Exception e) {
			// TODO: handle exception
			msg = "基础分页查询数据失败：" + e.getMessage();
			mylog.error(msg);
			result =  getReturnResult(msg, "", null);
		}
		
		return result;
	}
	
	
	/**
	 * 根据权限，查询分页数据，分步查询，第一步，根据权限查询车辆id，第二步，根据车辆id，查询相应数据
	 * @param jsonStr
	 * @return
	 */
	@RequestMapping("/selectPaginationDataByAuth.action")
	@ResponseBody
	public JsonMessage selectPaginationDataByAuth(@RequestBody String jsonStr) {
		JsonMessage result = null;
		String msg = "";
		try {
			Map map = JSONObject.fromObject(jsonStr);
			// 用于获取用户权限信息
			OnlineUser user = super.getOnlineUser();
			
			if(map.get("queryId") != null && user != null) {				
				//获取查询部门编号
				getBasicQueryData(user, map);
				
				String queryIdVeh = "alarmSlct.selectVehDatasByAuth";//根据权限，获取车辆id
				List list = new ArrayList<String> ();//车辆列表
				List vehList = queryService.query(queryIdVeh, map);
				if(vehList.size() > 0) {
					for(int i=0 ; i<vehList.size() ; i++) {
						Map temp = (Map) vehList.get(i);
						if(temp.containsKey("vehicleId")) {
							list.add(temp.get("vehicleId").toString());							
						}
					}
				}
				//整合map,去除已使用条件
				if(list.size() > 0){
					map.put("vehicleIdList", list);//车辆列表存入map
					map.remove("userId");
					map.remove("depId");
					map.remove("depIdList");					
				}
//				System.out.println("查询用参数：" + map.toString());
				//开始查询
				String queryId = map.get("queryId").toString();
				int pageNum = 1;//默认分页设置
				int pageSize = 0;
				if(map.get("pageNumber") != null) {
					pageNum = Integer.valueOf(map.get("pageNumber").toString());
				}
				if(map.get("pageSize") != null) {
					pageSize = Integer.valueOf(map.get("pageSize").toString());
				}
				if(pageSize > 0) {
					PaginateResult listPage = queryService.queryByPagination(queryId, map, pageNum, pageSize);					
					result = new JsonMessage(true,listPage);
				}else {
					msg += "分页数量参数获取失败！";
				}
				
				
			}else {
				msg += "根据权限查询分页数据失败：无法获取查询语句！";
			}
			
			
			//获取返回结果
			if(result == null) {
				result = getReturnResult(msg, "", null);
			}
		} catch (Exception e) {
			// TODO: handle exception
			msg += "根据权限查询分页数据失败，查询参数：" + jsonStr + " ， 失败原因：" + e.getMessage();
			mylog.error(msg);
			result = getReturnResult(msg,"",null);
		}
		

		return result;
	}
	
	
	
	/**
	 * <p>根据用户基本信息获取部门查询条件</p>
	 * <p>首先根据部门编号depId获取部门链表</p>
	 * <p>如果部门编号depId为空，则通过userId查询用户权限下所有部门</p>
	 * <p>把获取的数据放入map中，key为"depIdList"</p>
	 * @param user 当前用户
	 * @param map 查询条件集合
	 */
	private void getBasicQueryData(OnlineUser user, Map map) {
		if (user != null) {
			// 获取用户id
			long userId = user.getEntityId();
			map.put("userId", userId);
			// 根据用户id获取部门列表
			Integer depId = 0;
			if(map.get("depId") != null) {
				depId = Integer.valueOf(map.get("depId").toString());
			}

			if (depId > 0) {
				List<Long> depIdList = super.getDepartmentService().getDepIdList(depId);
				map.put("depIdList", depIdList);
				map.remove("depId");
			} else {
				// 如果部门编号为空，查询所有，那么通过userId获取部门编号
				if (userId > 0) {
					List<Department> list = super.getDepartmentService().getDepartmentListByUserId(userId);
					if (list.size() > 0) {
						List<Long> depIdList2 = new ArrayList<Long>();
						for (Department temp : list) {
							depIdList2.add(temp.getEntityId());
						}
						map.put("depIdList", depIdList2);
						map.remove("depId");
					}
				}
			} // end depId
		} // end user
	}	
}
